package SPAN::View::Chart;

use strict;
use warnings;

use Chart::Clicker;
use Chart::Clicker::Axis;
use Chart::Clicker::Data::DataSet;
use Chart::Clicker::Data::Series;
use Chart::Clicker::Decoration::Grid;
use Chart::Clicker::Decoration::Legend;
use Chart::Clicker::Decoration::LegendItem;
use Chart::Clicker::Decoration::Plot;
use Chart::Clicker::Drawing qw(:positions);
use Chart::Clicker::Drawing::Insets;
use Chart::Clicker::Renderer::Area;

use base 'Catalyst::View';

=head1 NAME

SPAN::View::Chart - Catalyst View

=head1 DESCRIPTION

Catalyst View.

=cut

my %content_type = ( svg => 'text/svg', png => 'image/png' );

sub process {
    my ( $self, $c ) = @_;

    my $graph = $c->stash->{graph};

    my $chart = new Chart::Clicker( { width => 500, height => 350 } );

    my $series = new Chart::Clicker::Data::Series(
        {   keys   => $graph->{x},
            values => $graph->{y},
            name   => $graph->{legend}
        }
    );

    my $dataset
        = new Chart::Clicker::Data::DataSet( { series => [$series] } );
    $chart->datasets( [$dataset] );

    my $legend = new Chart::Clicker::Decoration::Legend(
        { margins => new Chart::Clicker::Drawing::Insets( { top => 3 } ) } );
    $chart->add( $legend, $CC_BOTTOM );

    my $daxis = new Chart::Clicker::Axis(
        {   orientation => $CC_HORIZONTAL,
            position    => $CC_BOTTOM,
            visible     => 0,
            format      => '%u'
        }
    );
    $chart->add( $daxis, $CC_AXIS_BOTTOM );

    my $raxis = new Chart::Clicker::Axis(
        {   orientation => $CC_VERTICAL,
            position    => $CC_LEFT,
            format      => '%0.2f'
        }
    );
    $chart->add( $raxis, $CC_AXIS_LEFT );

    $chart->range_axes(  [$raxis] );
    $chart->domain_axes( [$daxis] );

    my $grid = new Chart::Clicker::Decoration::Grid();
    $chart->add( $grid, $CC_CENTER, 0 );

    my $renderer = new Chart::Clicker::Renderer::Area();
    $renderer->options( { fade => 1 } );

    my $plot = new Chart::Clicker::Decoration::Plot();
    $plot->renderers( [$renderer] );

    $chart->add( $plot, $CC_CENTER );

    $chart->prepare();
    $chart->draw();
    my $format = $graph->{format};
    $c->res->content_type( $content_type{$format} );
    $c->res->body( $chart->$format );
}

=head1 AUTHOR

Eden Cardoso Cardim,,,

=head1 LICENSE

This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

1;
